package com.moive.news.tqnewsapplication.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.moive.news.tqnewsapplication.R;
import com.moive.news.tqnewsapplication.base.BaseActivity;
import com.moive.news.tqnewsapplication.entity.DyReleaseEntity;
import com.moive.news.tqnewsapplication.entity.MyProInfo;
import com.moive.news.tqnewsapplication.entity.PinLunInfo;
import com.moive.news.tqnewsapplication.entity.ResourcesManager;
import com.moive.news.tqnewsapplication.networks.BaseApi;
import com.moive.news.tqnewsapplication.okmanager.OkManagerCallback;
import com.moive.news.tqnewsapplication.utils.DateUtil;
import com.moive.news.tqnewsapplication.utils.LogUtil;
import com.moive.news.tqnewsapplication.utils.PreferenceUtil;
import com.moive.news.tqnewsapplication.utils.TimeUtil;
import com.moive.news.tqnewsapplication.utils.ToastUtils;
import com.moive.news.tqnewsapplication.weight.MakeListView;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import onekeyshare.OnekeyShare;

/**
 * Created by Administrator on 2017/12/15.
 * 动态详情
 */

public class DymicDetilsActivity extends BaseActivity {
    @BindView(R.id.dymicdetils_back)
    ImageView dymicdetilsBack;
    @BindView(R.id.demic_relate)
    RelativeLayout demicRelate;
    @BindView(R.id.dymic_listview)
    ListView dymicListview;
    @BindView(R.id.chatContent)
    EditText chatContent;
    @BindView(R.id.voiceLayout)
    ImageView voiceLayout;
    @BindView(R.id.chatSendBtn)
    TextView chatSendBtn;
    @BindView(R.id.inputRelativeLayout)
    RelativeLayout inputRelativeLayout;
    private MyProInfo.DataBean dataBean;
    private String token = "", userimg = "", usernichen = "";
    List<PinLunInfo.DataBean> list = new ArrayList<>();
    private Gson gson = new Gson();
    private int type = -1, groupPosition01 = 0;
    private String id = "", parent_id = "";
    private Handler handler;
    private DymicListAdapter ads;
    private CircleImageView ad_mypro_img;
    private TextView ad_mypro_nichen;
    private TextView ad_mypro_time;
    private TextView ad_mypro_desrc;
    private NineGridView ad_mypro_nine;
    private LinearLayout mypro_fenxiang_ll;
    private LinearLayout mypro_pinglun_ll;
    private LinearLayout mypro_dianzan_ll;
    private TextView mypro_pinglun_text;
    private TextView mypro_dianzan_text;
    DymicList02Adapter adapter;
    private ImageView mypro_dianzan_img;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dymicdetils);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            dataBean = (MyProInfo.DataBean) intent.getSerializableExtra("data");
        }
        dymicdetilsBack.setOnClickListener(v -> finish());
        View view = getLayoutInflater().inflate(R.layout.adapter_mypro, null);
        ad_mypro_img = view.findViewById(R.id.ad_mypro_img);
        ad_mypro_nichen = view.findViewById(R.id.ad_mypro_nichen);
        ad_mypro_time = view.findViewById(R.id.ad_mypro_time);
        ad_mypro_desrc = view.findViewById(R.id.ad_mypro_desrc);
        ad_mypro_nine = view.findViewById(R.id.ad_mypro_nine);
        mypro_fenxiang_ll = view.findViewById(R.id.mypro_fenxiang_ll);
        mypro_pinglun_ll = view.findViewById(R.id.mypro_pinglun_ll);
        mypro_dianzan_ll = view.findViewById(R.id.mypro_dianzan_ll);
        mypro_pinglun_text = view.findViewById(R.id.mypro_pinglun_text);
        mypro_dianzan_text = view.findViewById(R.id.mypro_dianzan_text);
        mypro_dianzan_img = view.findViewById(R.id.mypro_dianzan_img);
        //评论
        mypro_pinglun_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (inputRelativeLayout.getVisibility() == View.GONE) {
                    inputRelativeLayout.setVisibility(View.VISIBLE);
                    type = 0;
                }
            }
        });
        //点赞
        mypro_dianzan_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dataBean.getIsCurrentUserLikes() == 1) {
                    ToastUtils.ShortToast("你已经点过赞了");

                }
                dianzhan();
            }
        });
        mypro_fenxiang_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onOneKeyShare(dataBean);
            }
        });

        Glide.with(DymicDetilsActivity.this)
                .load(dataBean.getUserHeadImg())
                .error(R.drawable.icon)
                .placeholder(R.drawable.icon)
                .into(ad_mypro_img);
        ad_mypro_nichen.setText(dataBean.getUsername());
        String time = DateUtil.getDescriptionTimeFromTimestamp(dataBean.getCreateDate());
        ad_mypro_time.setText(time);
        ad_mypro_desrc.setText(dataBean.getContent());
        ArrayList<ImageInfo> imageInfo = new ArrayList<>();
        List<MyProInfo.DataBean.ImagesBean> list = dataBean.getImages();
        for (MyProInfo.DataBean.ImagesBean imagesBean : list) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(imagesBean.getThumbUrl());
            info.setBigImageUrl(imagesBean.getLargeUrl());
            imageInfo.add(info);
        }
        ad_mypro_nine.setAdapter(new NineGridViewClickAdapter(DymicDetilsActivity.this, imageInfo));
        mypro_pinglun_text.setText(dataBean.getCommentCount() + "");
        mypro_dianzan_text.setText(dataBean.getLikesCount() + "");
        dymicListview.addHeaderView(view);
        if (dataBean.getIsCurrentUserLikes() == 1) {
            mypro_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan02);
        }
        chatContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() == 28) {
                    ToastUtils.ShortToast("你最多发送评论不超过28个字！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        getdata();
    }

    //分享
    private void onOneKeyShare(MyProInfo.DataBean item) {
        OnekeyShare oks = new OnekeyShare();
        oks.setText(item.getContent());
        oks.setTitle("爱小道分享");
        oks.setTitleUrl("www.tqiant.com");
        if (item.getImages().size() != 0 && item.getImages() != null) {
            oks.setImageUrl(item.getImages().get(0).getThumbUrl());
        } else {
            oks.setImageUrl("www.tqiant.com");
        }
        oks.setSilent(true);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " completed at " + msg;
                ToastUtils.ShortToast("分享成功！");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + "caught error at " + msg;
                ToastUtils.ShortToast("分享失败！");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " canceled at " + msg;
//                ToastUtils.ShortToast(text);
            }
        });
        Bitmap logo = BitmapFactory.decodeResource(DymicDetilsActivity.this.getResources(), R.mipmap.ic_launcher);
        String label = DymicDetilsActivity.this.getString(R.string.app_name);
        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {
                String text = "Customer Logo -- ShareSDK " + ShareSDK.getSDKVersionName();
                Toast.makeText(DymicDetilsActivity.this, text, Toast.LENGTH_SHORT).show();
            }
        };
        oks.setCustomerLogo(logo, label, listener);
        oks.show(DymicDetilsActivity.this);
    }

    //点赞
    private void dianzhan() {
        OkHttpUtils.post()
                .url(BaseApi.LIKE)
                .addParams("emotionsID", dataBean.getId())
                .addParams("token", PreferenceUtil.getString("token", ""))
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        int likes = dataBean.getLikesCount() + 1;
                        mypro_dianzan_text.setText(likes + "");
                        mypro_dianzan_img.setBackgroundResource(R.drawable.icon_dianzan02);
                    } else {
                        ToastUtils.ShortToast("你已经点过赞了");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    //获取动态详情
    private void getdata() {
        token = PreferenceUtil.getString("token", "");
        OkHttpUtils.post()
                .url(BaseApi.DYMADEL)
                .addParams("emotionID", dataBean.getId())
                .addParams("token", token)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        list.clear();
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject1 = (JSONObject) jsonArray.get(i);
                                PinLunInfo.DataBean dataBean1 = gson.fromJson(jsonObject1 + "", PinLunInfo.DataBean.class);
                                list.add(dataBean1);
                            }
                            ads = new DymicListAdapter(DymicDetilsActivity.this, list);
                            dymicListview.setAdapter(ads);
                            if (type == 1) {
                                adapter.notifyDataSetChanged();
                                type = -1;
                            } else if (type == 0) {

                                ads.notifyDataSetChanged();
                                type = -1;
                            }
                        }
                        if (jsonArray.length() == 0) {
                            ToastUtils.ShortToast("没有更多数据了！");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @OnClick({R.id.chatSendBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mypro_pinglun_ll:
                if (inputRelativeLayout.getVisibility() == View.GONE) {
                    inputRelativeLayout.setVisibility(View.VISIBLE);
                    type = 0;
                }
                break;
            case R.id.chatSendBtn:
                if (TextUtils.isEmpty(chatContent.getText().toString().trim())) {
                    ToastUtils.ShortToast("评论内容不能为空！");
                    return;
                }
                //发表父评论
                if (type == 0) {
                    comment(chatContent.getText().toString(), dataBean.getId(), "", "");
                } else {
                    //发表子评论
                    if (!TextUtils.isEmpty(id)) {
                        comment(chatContent.getText().toString(), "", parent_id, id);
                    }
                }
                break;
        }
    }

    //评论接口commit 评价内容 emotionID动态id ，parentCommentID父评论id,fromid 发给某人id
    private void comment(String commit, String emotionID, String parentCommentID, String fromid) {
        String token = PreferenceUtil.getString("token", "");
        OkHttpUtils.post()
                .url(BaseApi.COMMENT)
                .addParams("token", token)
                .addParams("emotionID", emotionID)
                .addParams("content", commit)
                .addParams("parentcommentid", parentCommentID)
                .addParams("toUserID", fromid)
                .build().execute(new OkManagerCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                LogUtil.e(TAG, e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                super.onResponse(response, id);
                LogUtil.i(TAG, response.toString());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optInt("code") == 0) {
                        ToastUtils.ShortToast("评论成功！");
                        getdata();
                        hideSoftKeyboard();
                        if (inputRelativeLayout.getVisibility() == View.VISIBLE) {
                            inputRelativeLayout.setVisibility(View.GONE);
                            chatContent.setText("");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public class DymicListAdapter extends BaseAdapter {
        private Context context;
        private List<PinLunInfo.DataBean> list;

        public DymicListAdapter(Context context, List<PinLunInfo.DataBean> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHelder viewHelder = null;
            if (viewHelder == null) {
                viewHelder = new ViewHelder();
                convertView = LayoutInflater.from(context).inflate(R.layout.expandablelistview_one, null);
                viewHelder.fromUser_name = convertView.findViewById(R.id.fromUser_name);
                viewHelder.fromUser_img = convertView.findViewById(R.id.fromUser_img);
                viewHelder.fromUser_comment = convertView.findViewById(R.id.fromUser_comment);
                viewHelder.dycommentHF = convertView.findViewById(R.id.dycommentHF);
                viewHelder.fromUser_time = convertView.findViewById(R.id.fromUser_time);
                viewHelder.makelistview = convertView.findViewById(R.id.makelistview);
                convertView.setTag(viewHelder);
            } else {
                viewHelder = (ViewHelder) convertView.getTag();
            }
            viewHelder.fromUser_name.setText(list.get(position).getFromUser().getNickname());
            viewHelder.fromUser_comment.setText(list.get(position).getContent());
            String time = TimeUtil.parseDateTime(list.get(position).getCreateDate());
            viewHelder.fromUser_time.setText(time);
            adapter = new DymicList02Adapter(context, list.get(position).getChildrenComments(), list.get(position).getId());
            viewHelder.makelistview.setAdapter(adapter);
            Glide.with(context)
                    .load(list.get(position).getFromUser().getHeadimg())
                    .centerCrop()
                    .dontAnimate()
                    .placeholder(R.drawable.icon)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(viewHelder.fromUser_img);
            viewHelder.dycommentHF.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (inputRelativeLayout.getVisibility() == View.GONE) {
                        inputRelativeLayout.setVisibility(View.VISIBLE);
                        type = 1;
                        //评论接口commit 评价内容 emotionID动态id ，parentCommentID父评论id,fromid 发给某人id
//                    private void comment(String commit, String emotionID, String parentCommentID, String fromid) {
                        id = list.get(position).getFromUser().getId();
                        parent_id = list.get(position).getId();
                    }
                }
            });
            return convertView;
        }

        class ViewHelder {
            private CircleImageView fromUser_img;
            private TextView fromUser_name;
            private TextView fromUser_comment;
            private TextView fromUser_time;
            private TextView dycommentHF;
            private MakeListView makelistview;
        }
    }

    public class DymicList02Adapter extends BaseAdapter {
        private Context context;
        private List<PinLunInfo.DataBean.ChildrenCommentsBean> childrenCommentsBeanList;
        private String page;

        public DymicList02Adapter(Context context, List<PinLunInfo.DataBean.ChildrenCommentsBean> childrenCommentsBeanList, String page) {
            this.context = context;
            this.childrenCommentsBeanList = childrenCommentsBeanList;
            this.page = page;
        }

        @Override
        public int getCount() {
            return childrenCommentsBeanList.size();
        }

        @Override
        public Object getItem(int position) {
            return childrenCommentsBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHodler02 viewHodler02 = null;
            if (viewHodler02 == null) {
                viewHodler02 = new ViewHodler02();
                convertView = LayoutInflater.from(context).inflate(R.layout.expandablelistview_two, null);
                viewHodler02.fromuser02_name = convertView.findViewById(R.id.fromuser02_name);
//                viewHodler02.fromUser02_comment = convertView.findViewById(R.id.fromUser02_comment);
//                viewHodler02.touser_name = convertView.findViewById(R.id.touser_name);

                convertView.setTag(viewHodler02);
            } else {
                viewHodler02 = (ViewHodler02) convertView.getTag();
            }

            viewHodler02.fromuser02_name.setText(childrenCommentsBeanList.get(position).getFromUser().getNickname() + "回复" +
                    childrenCommentsBeanList.get(position).getToUser().getNickname() + ":" + childrenCommentsBeanList.get(position).getContent());
            SpannableStringBuilder builder = new SpannableStringBuilder(viewHodler02.fromuser02_name.getText().toString());
//ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
            ForegroundColorSpan whiteSpan = new ForegroundColorSpan(getResources().getColor(R.color.theme));
            ForegroundColorSpan whiteSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.theme));
            ForegroundColorSpan blueSpan = new ForegroundColorSpan(getResources().getColor(R.color.help));
            String s = childrenCommentsBeanList.get(position).getFromUser().getNickname();
            String b = childrenCommentsBeanList.get(position).getToUser().getNickname();
            String c = childrenCommentsBeanList.get(position).getContent();
            builder.setSpan(whiteSpan, 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(blueSpan, s.length(), s.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(whiteSpan2, s.length() + 2, s.length() + 2 + b.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(blueSpan, s.length() + 2 + b.length(), s.length() + 2 + b.length() + c.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            viewHodler02.fromuser02_name.setText(builder);

//            viewHodler02.fromUser02_comment.setText(childrenCommentsBeanList.get(position).getContent());
//
//            viewHodler02.touser_name.setText(childrenCommentsBeanList.get(position).getToUser().getNickname());


            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (inputRelativeLayout.getVisibility() == View.GONE) {
                        inputRelativeLayout.setVisibility(View.VISIBLE);
                        type = 1;
                        id = childrenCommentsBeanList.get(position).getFromUser().getId();
                        parent_id = page;
                    }
                }
            });
            return convertView;
        }

        class ViewHodler02 {
            private TextView fromuser02_name;
//            private TextView touser_name;
//            private TextView fromUser02_comment;
        }
    }
}
